# -*- coding: utf-8 -*-
from hashlib import md5
from uuid import uuid4

from common.mch.model import *
from common.utils import track_logging
from common.utils.decorator import sql_wrapper

_LOGGER = track_logging.getLogger(__name__)
_SALT = u"V!$#s*PY"


def encode_password(passwd):
    return md5(passwd.encode('utf-8') + _SALT).hexdigest()


@sql_wrapper
def get_account(mch_id):
    return MchAccount.query.filter(MchAccount.id == mch_id).first()


@sql_wrapper
def create_account(name, pwd):
    account = MchAccount()
    account.name = name
    account.password = encode_password(pwd)
    account.api_key = uuid4().hex
    account.save()
    return account


@sql_wrapper
def create_mch_chn(mch_id, service_name, chns, notify_prefix):
    mch_chn = MchChannel()
    mch_chn.mch_id = mch_id
    mch_chn.service_name = service_name
    mch_chn.chns = ','.join(chns)
    mch_chn.notify_prefix = notify_prefix
    mch_chn.save()


@sql_wrapper
def get_mch_chn(mch_id, service_name):
    return MchChannel.query.filter(MchChannel.mch_id == mch_id).filter(
        MchChannel.service_name == service_name).first()


@sql_wrapper
def get_mch_test_chn_id(mch_id):
    item = MchChannel.query.filter(MchChannel.mch_id == mch_id).filter(
        MchChannel.service_name == 'test').first()
    if not item or not item.chns:
        return None
    return int(item.chns)


@sql_wrapper
def set_mch_test_chn_id(mch_id, channel_id):
    item = MchChannel.query.filter(MchChannel.mch_id == mch_id).filter(
        MchChannel.service_name == 'test').first()
    if item is None:
        return
    item.chns = str(channel_id)
    item.save()


@sql_wrapper
def get_mch_dct():
    mchs = MchAccount.query.all()
    mch_dct = {}
    for mch in mchs:
        mch_dct[mch.id] = mch.name
    return mch_dct
